package com.yc.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yc.entity.ClassInfo;
import com.yc.mapper.ClassInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Transient;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 处理学生毕业班级
 */
@Slf4j
@Configuration
@EnableScheduling //开启定时任务
public class StudentClassTask {

    @Autowired
    private ClassInfoMapper classInfoMapper;

    /**
     * 处理毕业班级
     */
    //@Scheduled(cron = "0 0/3 * * * ?")
    @Scheduled(cron = "0 10 1 * * ?")
    @Transient
    public void handleClassGraduation() throws ParseException {
        log.info("开始处理");
        LambdaQueryWrapper wrapper1 = Wrappers.<ClassInfo>lambdaQuery()
                .isNull(ClassInfo::getStatus).or().eq(ClassInfo::getStatus,"");
        List<ClassInfo> classList = classInfoMapper.selectList(wrapper1);
        List<Integer> list =new ArrayList<>();
        for (ClassInfo universityClass : classList) {
            String year = "20" + universityClass.getCname().substring(universityClass.getCname().length()-4,universityClass.getCname().length()-2);

            Calendar cal = Calendar.getInstance();
            //现在的日期
            Date date=new Date();
            cal.setTime(date);
            SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");

            Date d1 = sdformat.parse((Integer.valueOf(year)+4)+"-9-1");
            Date d2 = sdformat.parse(cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-1");

            if (d1.compareTo(d2) <0){
                list.add(Integer.valueOf(String.valueOf(universityClass.getId())));
            } else if (d1.compareTo(d2) == 0) {
                list.add(Integer.valueOf(String.valueOf(universityClass.getId())));
            }
        }
        if(list.size()>0){
            LambdaUpdateWrapper wrapper = Wrappers.<ClassInfo>lambdaUpdate()
                    .set(ClassInfo::getStatus,0).in(ClassInfo::getId,list);
            classInfoMapper.update(null,wrapper);
        }
        log.info("处理完毕");
    }
}
